package org.fer.solution.task;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.widget.Toast;

public class TaskProgress extends AsyncTask<String, Integer, Integer> {

	private ProgressDialog progressDialog;

	@Override
	protected void onPreExecute() {
		progressDialog.setProgress(0);
		progressDialog.setMax(100);
		progressDialog.show();
	}

	@Override
	protected Integer doInBackground(String... params) {
		/**
		 * Simularemos que descargamos un fichero mediante un sleep
		 */

		for (int i = 0; i < 100; i++) {
			// Simulamos cierto retraso
			try {
				Thread.sleep((int) Math.ceil(Math.random() * 100));
			} catch (InterruptedException e) {
			}

			publishProgress(i); // Actualizamos los valores
		}

		return 100;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		progressDialog.setProgress(values[0]);
	}

	@Override
	protected void onPostExecute(Integer result) {
		progressDialog.dismiss();

		Toast toast = Toast.makeText(progressDialog.getContext(), "Finalizada",
				Toast.LENGTH_LONG);
		toast.show();
	}

	public void setProgressDialog(ProgressDialog progressDialog) {
		this.progressDialog = progressDialog;
	}

}
